﻿
#region Using directives

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Xml;
using MCMLXVII.Core.Common;
using MCMLXVII.BackEnd.Services.Common.Messages;
using System.Xml.Serialization;
using Microsoft.Win32;
using System.Globalization;
using MCMLXVII.BackEnd.Services.SessionManagement.Messages;


#endregion


namespace MCMLXVII.Client.Common.Session
{

/*    public struct ServerInfo
    {
        public string ServerName;
        public string ConnectUsing;
        public string SubAddress;
        public bool IntegratedLogon;
        public string UserName;
        public string Password;
        public bool SavePassword;
        public DateTime LastLogon;
        public ServerInfo(string servername, string connectusing, string subaddress, bool integratedlogon, string username, string password, bool savepassword, DateTime lastlogon)
        {
            ServerName=servername ;
            ConnectUsing=connectusing ;
            SubAddress=subaddress;
            IntegratedLogon=integratedlogon ;
            UserName=username ;
            Password=password ;
            SavePassword=savepassword ;
            LastLogon=lastlogon ;
        }
    }
    */
    public class ToolSession
    {
      //  internal static List<ServerInfo> UserConnections;
      //  internal static int ActualServer;
      //  internal static string ActualServerName = "";
      //  internal static string AutomaticallyConnectTo;

      //  internal static Guid SessionGuid;
      //  internal static ServerInfo LastLogonInfo;
        public static string UserName;
        internal static string UserLang;
        internal static DateTime SessionExpiresOn;
        internal static string EngineVersion;
      //  internal static string ServerRedirectTo;
        internal static string[] ToolBehaviour;
        public static int MemberID;

        public static Proxy.BusinessActionsClient proxy = new MCMLXVII.Client.Common.Session.Proxy.BusinessActionsClient();
        /*
        private static ServerInfo GetCurrentServer()
        {
            if (ActualServer > -1)
                return UserConnections[ActualServer];
            else
                throw new FunctionalException(Properties.Resources.NotloggedOn);
        }

        private static void LoadUserData()
        {
            UserConnections = new List<ServerInfo>();
            ActualServer = -1;
            AutomaticallyConnectTo = "";

            RegistryKey Configkey = Registry.CurrentUser.OpenSubKey("MCMLXVII");
            if (Configkey != null) //First Connection
            {
                AutomaticallyConnectTo = Configkey.GetValue("AutoConnectTo", "").ToString();
                foreach (string key in Configkey.GetSubKeyNames())
                {
                    RegistryKey RKey = Configkey.OpenSubKey(key);
                    string ServerName = key;
                    string ConnectUsing = RKey.GetValue("ConnectionMethod", "Remoting").ToString();
                    string SubAddress = RKey.GetValue("SubAddress", "6000").ToString();
                    bool IntegratedLogon = bool.Parse(RKey.GetValue("IntegratedLogon", "True").ToString());
                    string UserName = RKey.GetValue("UserName", "").ToString();
                    string Password = RKey.GetValue("Password", "").ToString();
                    bool SavePassword = bool.Parse(RKey.GetValue("SavePassword","False").ToString());
                    DateTime LastLogon = DateTime.Parse(RKey.GetValue("LastLogon", DateTime.Now.ToUniversalTime().ToString()).ToString());
                    RKey.Close();
                    UserConnections.Add(new ServerInfo(ServerName, ConnectUsing, SubAddress, IntegratedLogon, UserName, Password, SavePassword, LastLogon));
                    if (AutomaticallyConnectTo == ServerName) 
                        ActualServer = UserConnections.Count - 1;
                }
                Configkey.Close();
            }
        }

        public static string ServerName()
        {
            return ActualServerName;
        }
        */
        public static string[] GetPermissions()
        {
            return ToolBehaviour;
        }        
        
        public static bool LogonUser(string ToolName)
        {
            /*
            LoadUserData();
            string Diag = "";
            if (ActualServer >= 0)
            {
                Diag = ConnectToServer(UserConnections[ActualServer], ToolName);
                if (Diag != "OK")
                    Diag = InteractiveLogon(UserConnections[ActualServer], ToolName);
                else
                    ActualServerName = UserConnections[ActualServer].ServerName;
            }
            else
                if (UserConnections.Count > 0)
                {
                    System.DateTime LastLogon = UserConnections[0].LastLogon;
                    int LastServer = 0;
                    for (int i = 1; i < UserConnections.Count; i++)
                    {
                        if (UserConnections[i].LastLogon > LastLogon)
                        {
                            LastServer = i;
                            LastLogon = UserConnections[i].LastLogon;
                        }
                    }
                    Diag = InteractiveLogon(UserConnections[LastServer], ToolName);
                }
                else */
            string Diag = InteractiveLogon(ToolName); 
            return (Diag=="OK");
        }
        /*
        public static string ConnectToServer(ServerInfo ConnectTo, string Tool, bool AutoConnect)
        {

            string resp = ConnectToServer(ConnectTo, Tool);
            if (resp == "OK")
                UpdateServerInfo(ConnectTo, AutoConnect);
            return resp;
        }
        */

        //public static string ConnectToServer(ServerInfo ConnectTo, string Tool)
        //{

        //    //IBackEndRequesterST RemSVC2 = (IBackEndRequesterST)ReqHelper.GetConnectorST(ConnectTo.ConnectUsing, ConnectTo.ServerName, ConnectTo.SubAddress);

        //    return ConnectToServer(ConnectTo, Tool, RemSVC2);
           
        //}
        /*
        public static string ConnectToServer(ServerInfo ConnectTo, string Tool, bool AutoConnect, Type Transport,string SPN)
        {
            ////sacar
            //ConnectTo.ServerName = "wxp-consult2";
            //IBackEndRequesterST RemSVC2 = (IBackEndRequesterST)ReqHelper.GetConnectorST(Transport, ConnectTo.ServerName, ConnectTo.SubAddress, SPN);
            
             string resp = ConnectToServer(ConnectTo, Tool);
            //System.Windows.Forms.MessageBox.Show(resp);
             if (resp == "OK")
                 UpdateServerInfo(ConnectTo, AutoConnect);
             return resp;
        }
        */
        public static string ConnectToServer(string Tool)
        {
            msgNewSessionResponse SessionResponse;
            try
            {
                SessionResponse =  proxy.GetNewSession(new msgNewSessionRequest(Tool));
                try {
                    CultureInfo ci = new CultureInfo(SessionResponse.Language);
                    System.Threading.Thread.CurrentThread.CurrentUICulture = ci;
                    System.Threading.Thread.CurrentThread.CurrentUICulture = ci;
                }
                catch
                { 
                    // Do nothing
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

            if (SessionResponse == null)
            {
                return "";
            }
            if (SessionResponse.Diag != "OK")
            {
                return SessionResponse.Diag;
            }
            else
            {
              //  SessionGuid = SessionResponse.SessionGUID;
              //  LastLogonInfo = ConnectTo;
                UserName = SessionResponse.UserName;
                UserLang = SessionResponse.Language;
                EngineVersion = SessionResponse.EngineVersion;
             //   ServerRedirectTo = SessionResponse.RedirectTo;
                SessionExpiresOn = SessionResponse.SessionExpiresOn;
                ToolBehaviour = SessionResponse.AllowedOperations;
                MemberID = SessionResponse.MemberID;
                return "OK";
            }
        }

        
        
        private static string InteractiveLogon(string ToolName)
        {
            frmLogon frm = new frmLogon(ToolName);
            if (frm.ShowDialog()==System.Windows.Forms.DialogResult.OK)                
                return "OK";
            else
                return Properties.Resources.LogonCanceled;
        }
        /*
        private static void UpdateServerInfo(ServerInfo si, bool AutoConnect )
        {
            ActualServerName = si.ServerName;
            RegistryKey Configkey = Registry.CurrentUser.OpenSubKey("MCMLXVII", true);
            if (Configkey == null) //First Connection
            {
                Configkey = Registry.CurrentUser.CreateSubKey("MCMLXVII");                
            }
            if (AutoConnect)
                Configkey.SetValue("AutoConnectTo", si.ServerName, RegistryValueKind.String);
            else
                Configkey.SetValue("AutoConnectTo", "", RegistryValueKind.String);
            RegistryKey ServerKey = Configkey.OpenSubKey(si.ServerName, true);
            if (ServerKey==null)
                ServerKey = Configkey.CreateSubKey(si.ServerName);
            ServerKey.SetValue("ConnectionMethod", si.ConnectUsing, RegistryValueKind.String);
            ServerKey.SetValue("SubAddress", si.SubAddress, RegistryValueKind.String) ;
            if (si.IntegratedLogon)
                ServerKey.SetValue("IntegratedLogon", bool.TrueString, RegistryValueKind.String);
            else
                ServerKey.SetValue("IntegratedLogon", bool.FalseString, RegistryValueKind.String);
            ServerKey.SetValue("UserName", si.UserName, RegistryValueKind.String);
            if (si.SavePassword)
                ServerKey.SetValue("Password", si.Password, RegistryValueKind.String);
            ServerKey.SetValue("LastLogon", DateTime.Now.ToUniversalTime().ToString(), RegistryValueKind.String);
            ServerKey.Close();
            Configkey.Close();
        }
         */ 
    }
}
